// let wsurl = "ws://82.157.123.54:9010/ajaxchattest";
let ws: any = null;
let weboscket_callback: any = null;
let isOpen: any = false;
// 此处为测试Id
const userinfo = localStorage.getItem("userInfo");
const userId = userinfo ? JSON.parse(userinfo).hhxsUserId : "";
var timer: any;
var wsUrl = "";
var isMySelf = false;
let errorNum = 0;

// let objId: any = null;

//获取 websocket 推送的数据
const websocketonmessage = (e: any) => {
  return weboscket_callback(e);
};

// 连接成功
const websocketonopen = () => {
  errorNum = 0;
  // console.log("连接 websocket 成功");
  isOpen = true;
  // 获取全部json
  ws.send(
    JSON.stringify({
      operationType: 1002,
    })
  );
  // 获取在线用户列表
  ws.send(
    JSON.stringify({
      operationType: 6001,
    })
  );
  // 获取全部锁列表
  ws.send(
    JSON.stringify({
      operationType: 5003,
    })
  );
};

// 连接失败时重新连接
const websocketonerror = (url: string) => {
  initWebSocket(url, weboscket_callback);
};

// 断开链接后报错
const websocketclose = async (e?: any, type?: any) => {
  errorNum = errorNum + 1;
  if (errorNum > 2) {
    alert("与服务器连接中断，请点击确认重新尝试连接");
    location.reload();
    return;
  }
  // console.log("断开连接", e);
  // ws = null;
  // await clearInterval(timer);
  // timer = null;

  if (isMySelf) return;
  await ws.close();
  await initWebSocket(wsUrl, weboscket_callback);
  // console.log("ws已断开连接，请重新连接");
  // if (type != "handle") {
  //   initWebSocket(wsUrl, weboscket_callback);
  // }
};

// 手动关闭 websocket
const closewebsocket = () => {
  ws.close();
  // ws = null;
  isMySelf = true;
  isOpen = false;
};

//初始化 websocket
const initWebSocket = (url: string, callback: any) => {
  wsUrl = url;
  ws = new WebSocket(url);
  ws.onmessage = websocketonmessage;
  ws.onopen = websocketonopen;
  ws.onerror = websocketonerror;
  ws.onclose = websocketclose;
  weboscket_callback = callback;
  timer = setInterval(wsHeartbeat, 30000);
};

const wsHeartbeat = () => {
  if (!isOpen) {
    clearInterval(timer);
    timer = null;
    return;
  }
  ws.send(
    JSON.stringify({
      operationType: 9999,
    })
  );
};

// 发送数据
const sendData = (data: any) => {
  //  判断 data 数据类型
  if (typeof data == "string") {
    data = data;
  } else {
    data = JSON.stringify(data);
  }
  //  判断 websocket 的状态
  if (ws.readyState === ws.OPEN) {
    // 已经打开,可以直接发送
    ws.send(data);
  } else if (ws.readyState === ws.CONNECTING) {
    // 正在开启状态中,则 1 秒后重新发送
    setTimeout(() => {
      ws.send(data);
    }, 1000);
  }
};

// 导出
export { initWebSocket, sendData, closewebsocket, websocketonopen };
